﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TlvLib.Packets;

namespace TlvLib
{
    public static class PacketIdKeeper
    {
        private static readonly ConcurrentDictionary<string, DateTime> ReceivedPacket 
            = new ConcurrentDictionary<string, DateTime>();

        public static bool IsDuplicated(LicensePlateInfo lpi)
        {
            var key = lpi.MonitorId + lpi.PacketId;
            var result = false;
            DateTime lastReceived;
            if (ReceivedPacket.TryGetValue(key, out lastReceived))
            {
                result = true;
            }
            else
            {
                ReceivedPacket.TryAdd(key, DateTime.Now);
            }


            RemoveAgedPacketId();

            return result;

        }

        
        private static void RemoveAgedPacketId()
        {
            var now = DateTime.Now;
            var thirtyMinutes = TimeSpan.FromMinutes(30);
            foreach (var receivedPacket in ReceivedPacket)
            {
                if (now - receivedPacket.Value > thirtyMinutes)
                {
                    DateTime dtAdded;
                    ReceivedPacket.TryRemove(receivedPacket.Key, out dtAdded);
                }
            }
            
        }

    }
}
